<?php
namespace app\pay\controller\fumin;

use pay\fumin\Config;
/*
 * 银联(微信)扫码支付（线下）
 */
class Wxsaoma extends Base {
    /*
     * 经畅远中转下单接口
     */
    public function index($data) {
        $verSign = $data['signature'];
        unset($data['signature']); 
        $data['signature'] = $this->changyuanSign($data); // 创建签名
        
        // 验证签名
        if($verSign == $data['signature']) {
            $ret = model('PayBis')->get(['merchant_id' => $data['mchntId']]);
            if($ret) {
                // 对数据进行解析，判断手续费、向富民平台请求等
                $res = $this->resData($data, $ret);
                return $res;
            }
        } else {
            $resArr = array(
                'msg'  => '签名验证失败',
                'code' => '401'
            );
            return json_encode($resArr, 320);
        }
    }
    
    /*
     * 对数据进行解析，判断手续费、向富民平台请求等
     */
    public function resData($data, $ret) {
        // 支付通道费率采用：畅远收费＋平台收费＋固定每笔费用
        $tollFee = floor($data['amount'] * ($ret->mchnt_fee_rate + $ret->pay_fee_rate) / 100) + $ret->mchnt_fee_fixed; // 手续费，floor向下取整

        if($ret->mchnt_fee < $tollFee) {
            $resArr = array(
                'msg'  => '支付通道使用费不足，请及时充值',
                'code' => '404'
            );
            return json_encode($resArr, 320); 
        } else {
            $Config = new Config();
            // 重新组装发送到富民的数据
            $dataToFumin = $this->reqFuminData($data, $Config->C('orderUrl'));
            $retData = json_decode($dataToFumin, true);
            if($retData['code'] == '10000') {
                // 将订单信息保存到数据库中
                $this->payBisOrderAdd($data, $retData['orderNo'], $tollFee);
                
                // 更新剩余可使用的通道费
                $newTollFee = array(
                    'mchnt_fee' => $ret->mchnt_fee - $tollFee
                );
                model('PayBis')->updateById($newTollFee, $ret->id);
            }
            return $dataToFumin;
        }    
    }

    /*
     * 订单信息添加
     */
    public function payBisOrderAdd($data, $orderNo, $tollFee) {
        // 订单有效时长
        if($data['timeoutExpress'] != null) {
            $paymentTime = $data['timeoutExpress'];
        } else {
            $paymentTime = null;
        }
        // 异步通知地址
        if($data['notifyUrl'] != null) {
            $notifyUrl = $data['notifyUrl'];
        } else {
            $notifyUrl = null;
        }
        $orderInfo = array(
            'pay_orderid'     => $orderNo, // 平台订单号
            'mchnt_order_no'  => $data['mchntOrderNo'], // 商户订单号
            'merchant_id'     => $data['mchntId'],
            'pay_amount'      => $data['amount'],
            'fee'             => $tollFee,
            'actual_amount'   => $data['amount'],
            'pay_tradetype'   => $data['payPowerId'],
            'payment_time'    => $paymentTime,
            'pay_callbackurl' => $notifyUrl,
        );
        model('PayBisOrder')->add($orderInfo);
    }
}

